package com.boarsoft.validate.jsonschema;

import com.boarsoft.config.core.CfgVarPullCallback;
import com.boarsoft.config.core.ConfigHttpPuller;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

public class JsonSchemaCache {
    private static ConcurrentHashMap<String, JsonSchema> schemaMap=new ConcurrentHashMap<>();

    public static JsonSchema getSchema(String schemaId){
        if(schemaMap.get(schemaId)==null){
            synchronized (schemaMap){
                if(schemaMap.get(schemaId)==null) {
                    String domain = System.getProperty("config.domain");
                    String appId = System.getProperty("app.id", "4028be7287036ef501870373971c0000");
                    String port = System.getProperty("port", "8083");
                    String env = System.getProperty("env" , "DEV");

                    ConfigHttpPuller.pullVars(domain, port, appId, env,  new CfgVarPullCallback() {
                        @Override
                        public boolean onReadFailed() {
                            throw new RuntimeException("failed found schema:"+schemaId);
                        }

                        @Override
                        public boolean callback(String k, String v, String g) {
                            if(g.equals("jsonSchema")){
                                JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7);
                                InputStream schemaStream = new ByteArrayInputStream(v.getBytes(StandardCharsets.UTF_8));
                                JsonSchema schema = factory.getSchema(schemaStream);
                                schemaMap.put(k,schema);
                            }
                            return true;
                        }
                    });

                }
            }
        }
        return schemaMap.get(schemaId);
    }
}
